package com.example.springsecuritydemo.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

/**
 * 自定义用户详情服务，
 * todo 重写根据登录名加载用户信息的方法
 */
@Component
public class DefinitionUserDetailsService implements UserDetailsService {

    /**
     * 通过密码解析器来对密码进行加密和匹配
     */
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        if (!username.equals("feng")) {
            throw new RuntimeException("改用户不存在");
        }
        String pwd = "123456";
        String encode = passwordEncoder.encode(pwd);

        boolean matches = passwordEncoder.matches(pwd, encode);
        System.out.println("是否匹配==》 " + matches);

        // 这个User对象，是UserDetails接口的一个实现类
        // todo 逗号分隔的字符串到权限列表(包含 权限 和 角色) ----- AuthorityUtils.commaSeparatedStringToAuthorityList("admin,normal,ROLE_test")
        User user = new User(username, encode, AuthorityUtils.commaSeparatedStringToAuthorityList("admin,normal,ROLE_test"));
        return user;
    }
}
